/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package connection;

import java.sql.*;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * @author Tung An
 */
public class DBConnection {

    String host = "";
    String username = "";
    String password = "";
    String database = "";
    Connection con = null;
    Statement st = null;
    ResultSet rs = null;

    public DBConnection(String host, String username, String password, String database) {
        this.host = host;
        this.username = username;
        this.password = password;
        this.database = database;
        this.con = this.getConnection();
    }

    protected Connection getConnection() {
        try {
            String url = "jdbc:mysql://" + host + ":3306/" + database;
            Class.forName("com.mysql.jdbc.Driver").newInstance();
            con = DriverManager.getConnection(url, username, password);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return con;
    }

    public ResultSet excuteQuery(String query) {
        try {
            rs = con.createStatement().executeQuery(query);
        } catch (SQLException ex) {
            Logger.getLogger(DBConnection.class.getName()).log(Level.SEVERE, null, ex);
        }
        return rs;
    }

    public PreparedStatement prepareStatement(String query) {
        PreparedStatement ppst = null;
        try {
            ppst = con.prepareStatement(query);
        } catch (SQLException ex) {
            Logger.getLogger(DBConnection.class.getName()).log(Level.SEVERE, null, ex);
        }
        return ppst;
    }

    public PreparedStatement prepareStatement(String query, Boolean output) {
        PreparedStatement ppst = null;
        try {
            if (output)
                ppst = con.prepareStatement(query, PreparedStatement.RETURN_GENERATED_KEYS);
            else
                ppst = con.prepareStatement(query);
        } catch (SQLException ex) {
            Logger.getLogger(DBConnection.class.getName()).log(Level.SEVERE, null, ex);
        }
        return ppst;
    }

    public void close() {
        try {
            if (rs != null && !rs.isClosed()) {
                rs.close();
            }

            if (con != null && con.isClosed()) {
                con.close();
            }
        } catch (SQLException ex) {
            Logger.getLogger(DBConnection.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}
